package com.yougou.ui.order;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.bumptech.glide.Glide;
import com.yougou.R;
import com.yougou.base.BaseActivity;
import com.yougou.data.model.Order;
import com.yougou.utils.OrderManager;
import com.yougou.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class OrderDetailActivity extends BaseActivity {
    
    public static final String EXTRA_ORDER_NUMBER = "extra_order_number";
    
    private Toolbar mToolbar;
    
    private ImageView mIvStatusIcon;
    private TextView mTvOrderStatus;
    private TextView mTvStatusDesc;
    
    private CardView mCardLogistics;
    private TextView mTvLogisticsCompany;
    private TextView mTvLogisticsNumber;
    private TextView mTvLogisticsStatus;
    
    private TextView mTvReceiverName;
    private TextView mTvReceiverPhone;
    private TextView mTvReceiverAddress;
    
    private ImageView mIvGoodsImage;
    private TextView mTvGoodsName;
    private TextView mTvGoodsPrice;
    private TextView mTvGoodsQuantity;
    
    private TextView mTvOrderNumber;
    private TextView mTvCreateTime;
    private TextView mTvGoodsTotal;
    private TextView mTvOrderTotal;
    
    private Button mBtnCancelOrder;
    private Button mBtnPay;
    private Button mBtnConfirmReceipt;
    private Button mBtnDeleteOrder;
    
    private Order mOrder;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        initView();
        initData();
    }
    
    @Override
    protected void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(v -> finish());
        
        // 订单状态
        mIvStatusIcon = findViewById(R.id.iv_status_icon);
        mTvOrderStatus = findViewById(R.id.tv_order_status);
        mTvStatusDesc = findViewById(R.id.tv_status_desc);
        
        // 物流信息
        mCardLogistics = findViewById(R.id.card_logistics);
        mTvLogisticsCompany = findViewById(R.id.tv_logistics_company);
        mTvLogisticsNumber = findViewById(R.id.tv_logistics_number);
        mTvLogisticsStatus = findViewById(R.id.tv_logistics_status);
        
        // 收货信息
        mTvReceiverName = findViewById(R.id.tv_receiver_name);
        mTvReceiverPhone = findViewById(R.id.tv_receiver_phone);
        mTvReceiverAddress = findViewById(R.id.tv_receiver_address);
        
        // 商品信息
        mIvGoodsImage = findViewById(R.id.iv_goods_image);
        mTvGoodsName = findViewById(R.id.tv_goods_name);
        mTvGoodsPrice = findViewById(R.id.tv_goods_price);
        mTvGoodsQuantity = findViewById(R.id.tv_goods_quantity);
        
        // 订单信息
        mTvOrderNumber = findViewById(R.id.tv_order_number);
        mTvCreateTime = findViewById(R.id.tv_create_time);
        mTvGoodsTotal = findViewById(R.id.tv_goods_total);
        mTvOrderTotal = findViewById(R.id.tv_order_total);
        
        // 操作按钮
        mBtnCancelOrder = findViewById(R.id.btn_cancel_order);
        mBtnPay = findViewById(R.id.btn_pay);
        mBtnConfirmReceipt = findViewById(R.id.btn_confirm_receipt);
        mBtnDeleteOrder = findViewById(R.id.btn_delete_order);
        
        // 按钮点击事件
        mBtnCancelOrder.setOnClickListener(v -> cancelOrder());
        mBtnPay.setOnClickListener(v -> payOrder());
        mBtnConfirmReceipt.setOnClickListener(v -> confirmReceipt());
        mBtnDeleteOrder.setOnClickListener(v -> deleteOrder());
    }
    
    @Override
    protected void initData() {
        String orderNumber = getIntent().getStringExtra(EXTRA_ORDER_NUMBER);
        if (orderNumber == null) {
            ToastUtils.show(this, "订单号不存在");
            finish();
            return;
        }
        
        // 加载订单详情
        mOrder = OrderManager.getOrderByNumber(orderNumber);
        if (mOrder == null) {
            ToastUtils.show(this, "订单不存在");
            finish();
            return;
        }
        
        updateUI();
    }
    
    
    private void updateUI() {
        if (mOrder == null) return;
        
        // 检查 Activity 是否还存在
        if (isFinishing() || isDestroyed()) {
            return;
        }
        
        // 更新订单状态
        updateOrderStatus();
        
        // 更新收货信息
        mTvReceiverName.setText(mOrder.getReceiverName());
        mTvReceiverPhone.setText(maskPhone(mOrder.getReceiverPhone()));
        mTvReceiverAddress.setText(mOrder.getReceiverAddress());
        
        // 更新商品信息
        mTvGoodsName.setText(mOrder.getGoodsName());
        mTvGoodsPrice.setText(String.format("¥%.2f", mOrder.getPrice()));
        mTvGoodsQuantity.setText("x" + mOrder.getQuantity());
        
        // 加载商品图片
        String imageUrl = mOrder.getImageUrl();
        if (imageUrl != null && !imageUrl.trim().isEmpty()) {
            // 使用 View 的 context 更安全
            Glide.with(mIvGoodsImage.getContext())
                    .load(imageUrl)
                    .placeholder(R.drawable.placeholder_image)
                    .error(R.drawable.placeholder_image)
                    .into(mIvGoodsImage);
        } else {
            mIvGoodsImage.setImageResource(R.drawable.placeholder_image);
        }
        
        // 更新订单信息
        mTvOrderNumber.setText(mOrder.getOrderNumber());
        mTvCreateTime.setText(formatTime(mOrder.getCreateTime()));
        
        double total = mOrder.getPrice() * mOrder.getQuantity();
        mTvGoodsTotal.setText(String.format("¥%.2f", total));
        mTvOrderTotal.setText(String.format("¥%.2f", total));
        
        // 更新操作按钮
        updateActionButtons();
    }
    
    
    private void updateOrderStatus() {
        int status = mOrder.getStatus();
        switch (status) {
            case 1: // 待付款
                mIvStatusIcon.setImageResource(R.drawable.ic_order_payment);
                mTvOrderStatus.setText("待付款");
                mTvStatusDesc.setText("请尽快完成支付");
                // 显示物流信息（待付款时隐藏）
                mCardLogistics.setVisibility(View.GONE);
                break;
            case 2: // 待发货
                mIvStatusIcon.setImageResource(R.drawable.ic_order_shipping);
                mTvOrderStatus.setText("待发货");
                mTvStatusDesc.setText("商家正在准备发货");
                mCardLogistics.setVisibility(View.GONE);
                break;
            case 3: // 待收货
                mIvStatusIcon.setImageResource(R.drawable.ic_order_receive);
                mTvOrderStatus.setText("待收货");
                mTvStatusDesc.setText("商品已发货，请注意查收");
                // 显示物流信息
                mCardLogistics.setVisibility(View.VISIBLE);
                mTvLogisticsCompany.setText("顺丰速运");
                mTvLogisticsNumber.setText("运单号：" + mOrder.getOrderNumber().substring(0, 12));
                mTvLogisticsStatus.setText("运输中");
                break;
            case 4: // 已完成
                mIvStatusIcon.setImageResource(R.drawable.ic_order_complete);
                mTvOrderStatus.setText("已完成");
                mTvStatusDesc.setText("交易成功");
                // 显示物流信息
                mCardLogistics.setVisibility(View.VISIBLE);
                mTvLogisticsCompany.setText("顺丰速运");
                mTvLogisticsNumber.setText("运单号：" + mOrder.getOrderNumber().substring(0, 12));
                mTvLogisticsStatus.setText("已签收");
                break;
        }
    }
    
    
    private void updateActionButtons() {
        // 隐藏所有按钮
        mBtnCancelOrder.setVisibility(View.GONE);
        mBtnPay.setVisibility(View.GONE);
        mBtnConfirmReceipt.setVisibility(View.GONE);
        mBtnDeleteOrder.setVisibility(View.GONE);
        
        int status = mOrder.getStatus();
        switch (status) {
            case 1: // 待付款
                mBtnCancelOrder.setVisibility(View.VISIBLE);
                mBtnPay.setVisibility(View.VISIBLE);
                break;
            case 2: // 待发货
                // 待发货时暂不支持取消（可根据需求调整）
                break;
            case 3: // 待收货
                mBtnConfirmReceipt.setVisibility(View.VISIBLE);
                break;
            case 4: // 已完成
                mBtnDeleteOrder.setVisibility(View.VISIBLE);
                break;
        }
    }
    
    
    private void cancelOrder() {
        // 更新订单状态为已取消（这里简化处理，直接删除）
        OrderManager.deleteOrder(mOrder.getOrderNumber());
        ToastUtils.show(this, "订单已取消");
        setResult(RESULT_OK);
        finish();
    }
    
    
    private void payOrder() {
        // 模拟支付成功并自动发货
        mOrder.setStatus(3); // 直接更新为待收货（自动发货）
        OrderManager.updateOrder(mOrder);
        ToastUtils.show(this, "支付成功，商品已自动发货");
        
        // 更新UI显示待收货状态和物流信息
        updateUI();
    }
    
    
    private void confirmReceipt() {
        mOrder.setStatus(4); // 更新为已完成
        OrderManager.updateOrder(mOrder);
        ToastUtils.show(this, "已确认收货");
        setResult(RESULT_OK);
        updateUI();
    }
    
    
    private void deleteOrder() {
        OrderManager.deleteOrder(mOrder.getOrderNumber());
        ToastUtils.show(this, "订单已删除");
        setResult(RESULT_OK);
        finish();
    }
    
    
    private String maskPhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
    
    
    private String formatTime(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        return sdf.format(new Date(timestamp));
    }
}

